package cn.anicert.zk.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import cn.anicert.zk.bean.Node;
import cn.anicert.zk.dao.NodeDao;
import cn.anicert.zk.util.ZooKeeperUtil;

@Repository("nodeDao")
public class NodeDaoImpl implements NodeDao {
    
    @Override
    public List<Node> getNodesByPath(String path) {
        List<String> child = ZooKeeperUtil.getChild(path);
        List<Node> listNodes = new ArrayList<Node>();
        for (String pathChild : child) {
            //获取该节点的内容
            String pathChildUrl = "";
            if (path.equals("/")) {
                pathChildUrl = "/" + pathChild;
            } else {
                pathChildUrl = path + "/" + pathChild;
            }
            Node node = ZooKeeperUtil.readData(pathChildUrl);
            node.setNodeName(pathChild);
            listNodes.add(node);
        }
        return listNodes;
    }
    
    @Override
    public boolean addNode(Node node) {
        boolean createZNode = ZooKeeperUtil.createZNode(node);
        if (createZNode) {
            return true;
        } else {
            return false;
        }
    }
    
    @Override
    public boolean deleteNode(Node node) {
        boolean deteleZKNode = ZooKeeperUtil.deteleZKNode(node.getNodePath());
        if (deteleZKNode) {
            return true;
        } else {
            return false;
        }
    }
    
    @Override
    public boolean updateNode(Node node) {
        boolean updateZKNodeData = ZooKeeperUtil.updateZKNodeData(node.getNodePath(),
            node.getNodeValue());
        if (updateZKNodeData) {
            return true;
        } else {
            return false;
        }
    }
    
    @Override
    public Node readData(String path) {
        Node node = ZooKeeperUtil.readData(path);
        return node;
    }
    
    @Override
    public boolean isExists(String path) {
        boolean exists = ZooKeeperUtil.isExists(path);
        if (exists) {
            return true;
        } else {
            return false;
        }
    }
    
}
